import HelpModal from './components/help-modal.js';

// 导出一个初始化函数
export function init(socket) {
    console.log('Room module initialized.');
    
    let helpModal; // 帮助弹窗实例

    // DOM 元素
    const currentRoomIdSpan = document.getElementById('current-room-id');
    const messageArea = document.getElementById('room-message-area');
    const playerListUl = document.getElementById('player-list');
    const leaveRoomBtn = document.getElementById('leave-room-btn');
    const inRoomGameSelect = document.getElementById('in-room-game-select');
    const startGameBtn = document.getElementById('start-game-btn');
    const rejoinGameBtn = document.getElementById('rejoin-game-btn');
    const helpSection = document.getElementById('help-section');

    // 1. 从 URL 中获取 roomId
    const urlParams = new URLSearchParams(window.location.search);
    console.log("urlParams:", urlParams);
    const roomId = urlParams.get('roomId');

    if (!roomId) {
        // 如果 URL 中没有 roomId，说明用户直接访问了这个页面，应该返回大厅
        updateMessage(document.getElementById('room-message-area'), '错误：房间ID不存在！', 'red');
        setTimeout(() => {
            window.dispatchEvent(new CustomEvent('navigate', { detail: { path: 'lobby.html' } }));
        }, 2000);
        return;
    }

    currentRoomIdSpan.textContent = roomId;

    const controller = new AbortController();
    const { signal } = controller;

    // 初始化帮助弹窗
    helpModal = new HelpModal();
    helpModal.init();

    function handleClick(event) {
        const clickedButton = event.target;

        if (clickedButton.id === 'leave-room-btn') {
            console.log('离开房间按钮被点击');
            socket.emit('leave_room', { roomId: roomId });
        } 
        else if (clickedButton.id === 'start-game-btn') {
            console.log('选择游戏按钮被点击, 选择的游戏为：', inRoomGameSelect.value);
            socket.emit('start_game', 
                { 
                    roomId: roomId, 
                    gameName: inRoomGameSelect.value 
                });
        }
        else if (clickedButton.id === 'rejoin-game-btn'){
            socket.emit('rejoin_game', 
                { 
                    roomId: roomId
                });
        }
        else if (clickedButton.classList.contains('help-game-btn')) {
            const game = clickedButton.dataset.game;
            console.log('说明书被点击:', game);
            if (helpModal) helpModal.destroy();
            let images = [];
            switch (game) {
                case 'geistes':
                    images = [
                        '/images/geistes/help1.png',
                        '/images/geistes/help2.png',
                        '/images/geistes/help3.png',
                        '/images/geistes/help4.png'
                    ];
                    break;
                default:
                    images = [];
            }
            helpModal = new HelpModal({ images });
            helpModal.init();
            helpModal.show();
        }
    }

    // 事件监听
    leaveRoomBtn.addEventListener('click', handleClick, { signal });
    startGameBtn.addEventListener('click', handleClick, { signal });
    rejoinGameBtn.addEventListener('click', handleClick, {signal});
    if (helpSection) helpSection.addEventListener('click', handleClick, { signal });

    window.roomController = controller;

    socket.on('player_joined', onPlyaerDataChanged);
    socket.on('update_players',  onPlyaerDataChanged);
    socket.on('player_left', onPlyaerDataChanged);
    socket.on('game_started', onStartGame);
    socket.on('room_left_success', onRoomLeftSuccess);
    
    // 刷新用户列表。
    socket.emit('request_players', { roomId: roomId });

    window.roomSocketListeners = {
        playerJoin:onPlyaerDataChanged,
        leftRoom: onRoomLeftSuccess,
        updatePlayer:onPlyaerDataChanged,
        gameStart:onStartGame,
        playerLeft:onPlyaerDataChanged
    };

    function onStartGame(data){
        const gameType = data.game;
        console.log("start game data:", data);
        console.log("gameType:", gameType);
        
        let gameViewPath;
        switch(gameType) {
            case 'geistes':
                gameViewPath = 'games/geistes.html';
                break;
            case 'tic_tac_toe':
                gameViewPath = 'games/tictactoe.html';
                break;
            case 'loveletter':
                gameViewPath = 'games/loveletter.html';
                break;
            default:
                console.error('未知的游戏类型:', gameType);
                return;
        }

        console.log("准备导航到:", gameViewPath);
        console.log("导航数据:", {
            path: gameViewPath,
            state: { 
                state: data.state,
                resource: data.resource,
                roomId: roomId,
                players: data.players,
             } 
        });

        const navigateEvent = new CustomEvent('navigate', {
                    detail: { 
                        path: gameViewPath,
                        state: { 
                            state: data.state,
                            playerState: data.playerState,
                            resource: data.resource,
                            roomId: roomId,
                            players: data.players,
                         } 
                    }
                });

        console.log("发送导航事件:", navigateEvent);
        window.dispatchEvent(navigateEvent);
    }

    function onPlyaerDataChanged(data){
        console.log("update player list");
        updatePlayerList(data.players);
        
        // 如果房主变更，刷新玩家列表以更新UI状态
        if (data.hostChanged) {
            console.log("房主变更，重新请求玩家列表以刷新UI");
            // 重新请求玩家列表，确保所有玩家都获得最新的房主信息
            setTimeout(() => {
                socket.emit('request_players', { roomId: roomId });
            }, 100);
        }
        
        updateUI(data);
        // 如果是房主，显示服务器发送的消息；非房主的消息由updateUI统一处理
        if (isHost && data.message) {
            updateMessage(data.message);
        }
    }

    function onRoomLeftSuccess(){
        const navigateEvent = new CustomEvent('navigate', {
                    detail: { path: 'lobby.html' }
                });

        window.dispatchEvent(navigateEvent);
    }

    function updateMessage(text, color = 'inherit') {
    messageArea.textContent = text;
    messageArea.style.color = color;
    }

    function updatePlayerList(players) {
    playerListUl.innerHTML = '';
    players.forEach(player => {
        const li = document.createElement('li');
        li.textContent = player.name;
        playerListUl.appendChild(li);
        });
    }

    let isHost = false; // 记录当前玩家是否是房主
    let hostName = ''; // 记录房主名字

    function updateUI(data) {
        // 更新房主信息（先更新，以便后续判断使用）
        if (data.hostId !== undefined) {
            const wasHost = isHost; // 记录之前是否是房主
            isHost = data.isHost === true;  // 明确检查是否为 true
            hostName = data.hostName || '';
            console.log('updateUI: isHost=', isHost, 'wasHost=', wasHost, 'hostName=', hostName, 'data.isHost=', data.isHost);
            
            // 如果房主状态发生变化，输出日志
            if (wasHost !== isHost) {
                console.log(`房主状态变化: ${wasHost ? '是房主' : '非房主'} -> ${isHost ? '是房主' : '非房主'}`);
            }
        }
        
        if (data.isGameStarted) {
            rejoinGameBtn.style.display = 'block';
            startGameBtn.style.display = 'none';
            inRoomGameSelect.style.display = 'none';
            document.getElementById('game-selection-section').querySelector('h3').style.display = 'none';
        }
        else{
            rejoinGameBtn.style.display = 'none';
            
            // 只有房主才能看到开始游戏设置
            if (isHost) {
                console.log('显示开始游戏按钮（房主）');
                startGameBtn.style.display = 'block';
                inRoomGameSelect.style.display = 'block';
                document.getElementById('game-selection-section').querySelector('h3').style.display = 'block';
            } else {
                console.log('隐藏开始游戏按钮，显示等待提示（非房主）');
                // 非房主显示等待房主的提示
                startGameBtn.style.display = 'none';
                inRoomGameSelect.style.display = 'none';
                document.getElementById('game-selection-section').querySelector('h3').style.display = 'none';
                if (hostName) {
                    updateMessage(`等待${hostName}选择桌游`, 'inherit');
                }
            }
        }
    }
}

// 导出一个清理函数
export function cleanup(socket) {
console.log('Room module cleaned up.');
    // 6. 在 cleanup 时，调用 abort() 移除所有监听器
    if (window.roomController) {
        window.roomController.abort();
        console.log('Room event listeners have been aborted.');
        delete window.roomController;
    }

    if (window.roomSocketListeners) {
        socket.off('room_left_success', window.roomSocketListeners.leftRoom);
        socket.off('player_joined', window.roomSocketListeners.playerJoin);
        socket.off('update_players', window.roomSocketListeners.updatePlayer);
        socket.off('game_started', window.roomSocketListeners.gameStart);
        socket.off('player_left', window.roomSocketListeners.playerLeft);
        delete window.roomSocketListeners;
    }

    // 清理帮助弹窗
    if (helpModal) {
        helpModal.destroy();
    }
}